"""
进程CRUD操作
"""
from sqlalchemy.orm import Session
from app.models.process import Process
from typing import Optional, List

def get_process_by_id(db: Session, process_id: int) -> Optional[Process]:
    """根据ID获取进程"""
    return db.query(Process).filter(Process.id == process_id).first()

def get_processes_by_machine_id(db: Session, machine_id: int) -> List[Process]:
    """根据机器ID获取进程列表"""
    return db.query(Process).filter(Process.machine_id == machine_id).all()

def get_processes_by_machine_id_limit(db: Session, machine_id: int, limit: int = 100) -> List[Process]:
    """根据机器ID获取进程列表(限制数量)"""
    return db.query(Process).filter(Process.machine_id == machine_id).order_by(Process.collected_at.desc()).limit(limit).all()

def get_all_processes(db: Session, skip: int = 0, limit: int = 100) -> List[Process]:
    """获取所有进程列表"""
    return db.query(Process).offset(skip).limit(limit).all()

def create_process(db: Session, process_data: dict) -> Process:
    """创建进程"""
    db_process = Process(**process_data)
    db.add(db_process)
    db.commit()
    db.refresh(db_process)
    return db_process

def create_processes_bulk(db: Session, processes_data: List[dict]) -> List[Process]:
    """批量创建进程"""
    db_processes = [Process(**process_data) for process_data in processes_data]
    db.add_all(db_processes)
    db.commit()
    for process in db_processes:
        db.refresh(process)
    return db_processes

def update_process(db: Session, process_id: int, process_data: dict) -> Optional[Process]:
    """更新进程信息"""
    db_process = get_process_by_id(db, process_id)
    if db_process:
        for key, value in process_data.items():
            setattr(db_process, key, value)
        db.commit()
        db.refresh(db_process)
    return db_process

def delete_process(db: Session, process_id: int) -> bool:
    """删除进程"""
    db_process = get_process_by_id(db, process_id)
    if db_process:
        db.delete(db_process)
        db.commit()
        return True
    return False

def delete_processes_by_machine_id(db: Session, machine_id: int) -> int:
    """根据机器ID删除进程"""
    count = db.query(Process).filter(Process.machine_id == machine_id).delete()
    db.commit()
    return count